package com.pdf.pdfserver.config;

import com.pdf.pdfserver.intecepter.SolrAuthInterceptor;
import com.pdf.pdfserver.vo.SolrHostVO;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.MalformedURLException;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/10
 */
@Configuration
public class SolrContext {


    @Value(value = "${spring.data.solr.host}")
    private String solrUrl;

    @Value(value = "${spring.data.solr.data_core}")
    private String dataCore;

    @Autowired
    private SolrAuthInterceptor solrAuthInterceptor;

    @Bean
    public HttpSolrClient httpSolrClient() throws MalformedURLException {

        CredentialsProvider provider = new BasicCredentialsProvider();
        SolrHostVO solrHostVO = new SolrHostVO().parse(this.solrUrl);
        provider.setCredentials(new AuthScope(solrHostVO.getHost(), solrHostVO.getPort()),
                new UsernamePasswordCredentials(solrHostVO.getUserName(), solrHostVO.getPassword()));
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultCredentialsProvider(provider);
        // 指定拦截器，用于设置认证信息
        builder.addInterceptorFirst(this.solrAuthInterceptor);
        CloseableHttpClient httpClient = builder.build();
        HttpSolrClient client = new HttpSolrClient.Builder(this.solrUrl).withHttpClient(httpClient).build();

        return client;

    }

    public String getSolrUrl() {
        return solrUrl;
    }

    public void setSolrUrl(String solrUrl) {
        this.solrUrl = solrUrl;
    }

    public String getDataCore() {
        return dataCore;
    }

    public void setDataCore(String dataCore) {
        this.dataCore = dataCore;
    }
}